/*
 * Copyright 2014-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.micro.shop.core;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.micro.shop.utils.MyStringUtils;

/**
 * api错误信息
 * <pre>{
 * 	httpCode: 'int: http状态码，如果定义，http返回码，将使用此值',
 * 	code: '错误码',
 * 	msg: '错误说明',
 * 	data: 'json: 期望传递的数据',
 * 	errors: [{
 * 		//错误详情
 * 	}]
 * }</pre>
 */
public class ErrorMsg extends HashMap<String,Object> implements Serializable {
	private static final long serialVersionUID = 1L;
	public Integer getHttpCode() {
		return (Integer) this.get("httpCode");
	}
	public void setHttpCode(int httpCode) {
		this.put("httpCode", httpCode);
	}
	public String getCode() {
		return (String) this.get("code");
	}
	public void setCode(String code) {
		this.put("code", code);
	}
	public String getErrorCode() {
		return (String) this.get("errorCode");
	}
	public void setErrorCode(String errorCode) {
		this.put("errorCode", errorCode);
	}
	public String getMsg() {
		return (String) this.get("msg");
	}
	public void setMsg(String msg) {
		this.put("msg", msg);
	}
	
	public ErrorMsg() {
		
	}
	public ErrorMsg(String code, String msg) {
		setCode(code);
		setMsg(msg);
	}
	
	public ErrorMsg(String code,String errorCode, String msg) {
		setCode(code);
		setErrorCode(errorCode);
		setMsg(msg);
	}
	
	public ErrorMsg(Integer httpCode, String code, String msg) {
		if (httpCode != null) setHttpCode(httpCode);
		setCode(code);
		setMsg(msg);
	}
	
	public ErrorMsg(Exception ex) {
		String msg = ex.getMessage();
		if (MyStringUtils.isEmpty(msg)) msg = ex.toString();
		setMsg(msg);
		if (ex instanceof IllegalArgumentException) {
			setHttpCode(400);
		} else if (ex instanceof IllegalStateException) {
			setHttpCode(503);
		}
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> getData() {
		Map<String, Object> data = (Map<String, Object>) this.get("data");
		if (data == null) {
			data = new HashMap<>();
			this.put("data", data);
		}
		return data;
	}
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getErrors() {
		List<Map<String, Object>> errors = (List<Map<String, Object>>) this.get("errors");
		if (errors == null) {
			errors = new ArrayList<>();
			this.put("errors", errors);
		}
		return errors;
	}
	

}
